<template>
  <div class="profile-container">
    <button class="back-home-btn" @click="goHome">返回首页</button>
    <div class="profile-layout">
      <!-- 左侧菜单 -->
      <aside class="profile-sidebar">
        <div class="avatar-box">
          <img class="avatar" :src="getAvatarUrl(user.avatar)" alt="头像">
          <div class="username">{{ user.username || '未登录' }}</div>
        </div>
        <ul class="profile-menu">
          <li :class="{active: activeTab==='base'}" @click="activeTab='base'">基础信息</li>
          <li class="logout-btn" @click="handleLogout">退出登录</li>
        </ul>
      </aside>
      <!-- 右侧内容区 -->
      <main class="profile-main">
        <div v-if="activeTab==='base'">
          <form class="base-info-form" @submit.prevent="saveBaseInfo">
            <div class="form-row">
              <label>用户名</label>
              <input v-model="editUser.username" required />
            </div>
            <div class="form-row">
              <label>邮箱</label>
              <input v-model="editUser.email" type="email" required />
            </div>
            <div class="form-row">
              <label>手机号</label>
              <input v-model="editUser.phone" />
            </div>
            <div class="form-row">
              <label>学号</label>
              <input v-model="editUser.studentId" disabled />
            </div>
            <div class="form-row">
              <label>头像</label>
              <div class="avatar-upload-box">
                <img :src="getAvatarUrl(editUser.avatar)" class="avatar-preview" alt="头像预览" />
                <input type="file" accept="image/*" @change="onAvatarChange" />
              </div>
            </div>
            <button class="save-btn" type="submit">保存修改</button>
            <span v-if="baseInfoMsg" class="base-info-msg">{{ baseInfoMsg }}</span>
          </form>
        </div>
      </main>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router';
const router = useRouter();
const goHome = () => {
  router.push('/');
};
import { ref, onMounted } from 'vue';
import axios from 'axios';
import moment from 'moment';

const defaultAvatar = '';

const user = ref({ username: '', avatar: '', email: '', phone: '', studentId: '' });
const editUser = ref({ username: '', avatar: '', email: '', phone: '', studentId: '' });
const activeTab = ref('base');
const baseInfoMsg = ref('');


const fetchProfile = async () => {
  const token = localStorage.getItem('token');
  try {
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [个人资料] 请求获取用户信息: /api/auth/profile`);
    const res = await axios.get('/api/auth/profile', {
      headers: { ...(token ? { 'Authorization': `Bearer ${token}` } : {}) }
    });
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [个人资料] 获取用户信息成功:`, res.data.user);
    user.value = res.data.user || { username: '', avatar: '', email: '', phone: '', studentId: '' };
    Object.assign(editUser.value, user.value);
  } catch (err: any) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [个人资料] 获取用户信息失败:`, err);
    user.value = { username: '', avatar: '', email: '', phone: '', studentId: '' };
  }
};

onMounted(() => {
  fetchProfile();
});

const saveBaseInfo = async () => {
  baseInfoMsg.value = '';
  const token = localStorage.getItem('token');
  try {
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [个人资料] 请求更新用户信息:`, editUser.value);
    const res = await axios.post('/api/auth/update', editUser.value, {
      headers: { ...(token ? { 'Authorization': `Bearer ${token}` } : {}) }
    });
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [个人资料] 更新用户信息响应:`, res.data);
    if (res.data.success) {
      baseInfoMsg.value = '保存成功';
      fetchProfile();
    } else {
      baseInfoMsg.value = res.data.message || '保存失败';
      console.warn(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [WARN] [个人资料] 保存基础信息失败:`, res.data);
    }
  } catch (err: any) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [个人资料] 保存基础信息异常:`, err, err?.response?.data);
    baseInfoMsg.value = err.response?.data?.message || '保存失败';
  }
};


const handleLogout = async () => {
  const token = localStorage.getItem('token');
  try {
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [个人资料] 请求用户登出`);
    const res = await axios.post('/api/auth/logout', {}, {
      headers: { ...(token ? { 'Authorization': `Bearer ${token}` } : {}) }
    });
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [个人资料] 用户登出响应:`, res.data);
    if (res.status === 200 && res.data.message === '登出成功') {
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      window.location.href = '/login';
    } else {
      alert(res.data.message || '退出登录失败');
      console.warn(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [WARN] [个人资料] 登出失败:`, res.data);
    }
  } catch (err) {
    const e = err as any;
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [个人资料] 登出异常:`, e);
    alert((e.response && e.response.data && e.response.data.message) || '网络错误，退出登录失败');
  }
};

const onAvatarChange = async (e: Event) => {
  const files = (e.target as HTMLInputElement).files;
  if (!files || files.length === 0) return;
  const file = files[0];
  const token = localStorage.getItem('token');
  const formData = new FormData();
  formData.append('avatar', file);
  try {
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [个人资料] 请求上传头像: ${file.name}`);
    const res = await axios.post('/api/auth/avatar', formData, {
      headers: { ...(token ? { 'Authorization': `Bearer ${token}` } : {}), 'Content-Type': 'multipart/form-data' }
    });
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [个人资料] 头像上传响应:`, res.data);
    if (res.data.success && res.data.url) {
      editUser.value.avatar = res.data.url;
      baseInfoMsg.value = '头像上传成功';
      // 同步 localStorage.user，确保导航栏实时显示新头像
      const userStr = localStorage.getItem('user');
      if (userStr) {
        const userObj = JSON.parse(userStr);
        userObj.avatar = res.data.url;
        localStorage.setItem('user', JSON.stringify(userObj));
      }
    } else {
      baseInfoMsg.value = res.data.message || '头像上传失败';
      console.warn(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [WARN] [个人资料] 头像上传失败:`, res.data);
    }
  } catch (err: any) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [个人资料] 头像上传异常:`, err, err?.response?.data);
    baseInfoMsg.value = err.response?.data?.message || '头像上传失败';
  }
};

// 拼接完整头像地址
const API_BASE = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000';
const getAvatarUrl = (avatar: string) => {
  if (!avatar) return defaultAvatar;
  if (avatar.startsWith('http') || avatar.startsWith('data:')) return avatar;
  if (avatar.startsWith('/uploads/')) return API_BASE + avatar;
  return defaultAvatar;
};
</script>

<style scoped>
.back-home-btn {
  position: fixed;
  top: 20px;
  left: 30px;
  z-index: 2000;
  padding: 8px 18px;
  background: #2563eb;
  color: #fff;
  border: none;
  border-radius: 6px;
  font-size: 15px;
  font-weight: 600;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  transition: background 0.2s;
}
.back-home-btn:hover {
  background: #1d4ed8;
}
.profile-container {
  max-width: 100vw;
  margin: 0 auto;
  padding: 0 2vw;
  background-color: #fff;
  box-sizing: border-box;
  min-height: 100vh;
}

.profile-layout {
  display: flex;
  min-height: 80vh;
  margin-top: 60px;
}

.profile-sidebar {
  flex: 3;
  max-width: 260px;
  background: #f8fafc;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  padding: 32px 0 32px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 32px;
  min-width: 180px;
}

.avatar-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 32px;
}
.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #e2e8f0;
  margin-bottom: 12px;
}
.username {
  font-weight: 600;
  color: #333;
  font-size: 18px;
}
.profile-menu {
  list-style: none;
  padding: 0;
  width: 100%;
}
.profile-menu li {
  width: 100%;
  padding: 14px 0 14px 32px;
  color: #475569;
  font-size: 16px;
  cursor: pointer;
  transition: background 0.2s, color 0.2s;
  border-left: 4px solid transparent;
}
.profile-menu li.active {
  background: #e0e7ef;
  color: #2563eb;
  border-left: 4px solid #2563eb;
}
.profile-menu .logout-btn {
  color: #ef4444;
  margin-top: 40px;
  font-weight: 600;
  border-left: 4px solid transparent;
}
.profile-menu .logout-btn:hover {
  background: #fee2e2;
  color: #b91c1c;
}
.profile-main {
  flex: 7;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  padding: 40px 32px;
  min-height: 400px;
}
</style>
<style scoped>
.avatar-upload-box {
  display: flex;
  align-items: center;
  gap: 16px;
}
.avatar-preview {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
  border: 1.5px solid #e2e8f0;
}
</style>
<style scoped>
.base-info-form {
  max-width: 400px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 18px;
}
.form-row {
  display: flex;
  flex-direction: column;
  gap: 6px;
}
.form-row label {
  color: #475569;
  font-weight: 500;
}
.form-row input {
  padding: 10px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  font-size: 15px;
}
.form-row input:disabled {
  background: #f1f5f9;
}
.save-btn {
  margin-top: 10px;
  padding: 10px;
  background: #2563eb;
  color: #fff;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: background 0.2s;
}
.save-btn:hover {
  background: #1d4ed8;
}
.base-info-msg {
  color: #16a34a;
  margin-left: 10px;
}
</style>
